<template>
  <div class="dashboard">
    <!-- 顶部导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary fixed-top">
      <div class="container-fluid">
        <router-link class="navbar-brand" to="/">
          <img src="/static/fylog1d.png" alt="Logo" width="32" height="32" class="d-inline-block align-text-top me-2">
          柳州市妇幼保健院退费审核管理系统
        </router-link>
        
        <div class="navbar-nav ms-auto">
          <div class="nav-item dropdown" ref="userDropdown">
            <a 
              class="nav-link dropdown-toggle" 
              href="#" 
              role="button" 
              @click.prevent="toggleDropdown"
              :aria-expanded="dropdownOpen"
            >
              <i class="bi bi-person-circle"></i> 
              <span>{{ authStore.user?.username || '管理员' }}</span>
            </a>
            <ul class="dropdown-menu dropdown-menu-end" :class="{ show: dropdownOpen }">
              <li>
                <h6 class="dropdown-header">
                  <i class="bi bi-person-circle"></i> {{ authStore.user?.fullName || authStore.user?.username || '管理员' }}
                </h6>
              </li>
              <li><hr class="dropdown-divider"></li>
              <li>
                <a class="dropdown-item" href="#" @click.prevent="handleLogout">
                  <i class="bi bi-box-arrow-right"></i> 退出登录
                </a>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </nav>

    <div class="container-fluid main-content">
      <div class="row">
        <!-- 左侧导航栏 -->
        <nav class="col-md-3 col-lg-2 d-md-block bg-light sidebar">
          <div class="position-sticky pt-3">
            <ul class="nav flex-column">
              <li class="nav-item">
                <router-link 
                  class="nav-link" 
                  to="/refund"
                  active-class="active"
                >
                  <i class="bi bi-cash-coin"></i>
                  <span>退款审核管理</span>
                </router-link>
              </li>
              <!-- 临时隐藏退款任务管理 -->
              <!-- <li class="nav-item">
                <router-link 
                  class="nav-link" 
                  to="/refund-task"
                  active-class="active"
                >
                  <i class="bi bi-list-task"></i>
                  <span>退款任务管理</span>
                </router-link>
              </li> -->
              <li class="nav-item">
                <router-link 
                  class="nav-link" 
                  to="/statistics"
                  active-class="active"
                >
                  <i class="bi bi-bar-chart"></i>
                  <span>汇总统计</span>
                </router-link>
              </li>
              <li class="nav-item">
                <router-link 
                  class="nav-link" 
                  to="/dictionary"
                  active-class="active"
                >
                  <i class="bi bi-book"></i>
                  <span>字典设置</span>
                </router-link>
              </li>
              <li class="nav-item">
                <router-link 
                  class="nav-link" 
                  to="/his-verify"
                  active-class="active"
                >
                  <i class="bi bi-shield-check"></i>
                  <span>HIS退款验证</span>
                </router-link>
              </li>
              <li class="nav-item">
                <router-link 
                  class="nav-link" 
                  to="/refund-report"
                  active-class="active"
                >
                  <i class="bi bi-file-earmark-bar-graph"></i>
                  <span>退费报表管理</span>
                </router-link>
              </li>
              <li class="nav-item">
                <router-link 
                  class="nav-link" 
                  to="/refund-export-report"
                  active-class="active"
                >
                  <i class="bi bi-file-earmark-spreadsheet"></i>
                  <span>财务报表导出</span>
                </router-link>
              </li>
              <li class="nav-item">
                <router-link 
                  class="nav-link" 
                  to="/refund-task-completion"
                  active-class="active"
                >
                  <i class="bi bi-clipboard-check"></i>
                  <span>退费任务完成情况</span>
                </router-link>
              </li>
              <li class="nav-item">
                <router-link 
                  class="nav-link" 
                  to="/task-adjustment"
                  active-class="active"
                >
                  <i class="bi bi-gear"></i>
                  <span>工作任务调整</span>
                </router-link>
              </li>
            </ul>
          </div>
        </nav>

        <!-- 主内容区域 -->
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
          <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
            <h1 class="h2">{{ pageTitle }}</h1>
            <div class="btn-toolbar mb-2 mb-md-0">
              <div class="btn-group me-2">
                <button 
                  type="button" 
                  class="btn btn-sm btn-outline-secondary" 
                  @click="refreshPage"
                >
                  <i class="bi bi-arrow-clockwise"></i> 刷新
                </button>
              </div>
            </div>
          </div>

          <!-- 标签页导航 -->
          <div class="tab-navigation mb-3" v-if="openTabs.length > 0">
            <ul class="nav nav-tabs">
              <li class="nav-item" v-for="tab in openTabs" :key="tab.path">
                <a 
                  class="nav-link d-flex align-items-center" 
                  :class="{ active: tab.path === currentPath }"
                  href="#" 
                  @click.prevent="switchTab(tab.path)"
                >
                  <i :class="tab.icon" class="me-2"></i>
                  <span>{{ tab.title }}</span>
                  <button 
                    type="button" 
                    class="btn-close btn-close-sm ms-2" 
                    @click.stop="closeTab(tab.path)"
                    v-if="openTabs.length > 1"
                    aria-label="关闭标签页"
                  ></button>
                </a>
              </li>
            </ul>
          </div>

          <!-- 子路由内容 -->
          <div class="page-content">
            <router-view />
          </div>
        </main>
      </div>
    </div>

    <!-- Toast 容器 -->
    <div class="toast-container position-fixed top-0 end-0 p-3" id="toastContainer"></div>
  </div>
</template>

<script setup>
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()

// 页面配置映射
const pageConfigs = {
  'RefundManagement': {
    title: '退款审核管理',
    icon: 'bi bi-cash-coin',
    path: '/refund'
  },
  // 'RefundTaskManagement': {
  //   title: '退款任务管理',
  //   icon: 'bi bi-list-task',
  //   path: '/refund-task'
  // }, // 临时隐藏退款任务管理
  'Statistics': {
    title: '汇总统计',
    icon: 'bi bi-bar-chart',
    path: '/statistics'
  },
  'Dictionary': {
    title: '字典设置',
    icon: 'bi bi-book',
    path: '/dictionary'
  },
  'HisRefundVerify': {
    title: 'HIS退款验证',
    icon: 'bi bi-shield-check',
    path: '/his-verify'
  },
  'RefundReport': {
    title: '退费报表管理',
    icon: 'bi bi-file-earmark-bar-graph',
    path: '/refund-report'
  },
  'RefundExportReport': {
    title: '财务报表导出',
    icon: 'bi bi-file-earmark-spreadsheet',
    path: '/refund-export-report'
  },
  'RefundTaskCompletion': {
    title: '退费任务完成情况',
    icon: 'bi bi-clipboard-check',
    path: '/refund-task-completion'
  },
  'TaskAdjustment': {
    title: '工作任务调整',
    icon: 'bi bi-gear',
    path: '/task-adjustment'
  }
}

// 标签页管理
const openTabs = ref([])
const currentPath = computed(() => route.path)

// 下拉菜单状态
const dropdownOpen = ref(false)
const userDropdown = ref(null)

const pageTitle = computed(() => {
  const config = pageConfigs[route.name]
  return config ? config.title : '退款审核管理'
})

// 添加标签页
const addTab = (routeName, routePath) => {
  const config = pageConfigs[routeName]
  if (!config) return
  
  const existingTab = openTabs.value.find(tab => tab.path === routePath)
  if (!existingTab) {
    openTabs.value.push({
      title: config.title,
      icon: config.icon,
      path: routePath,
      name: routeName
    })
  }
}

// 切换标签页
const switchTab = (path) => {
  router.push(path)
}

// 关闭标签页
const closeTab = (path) => {
  const tabIndex = openTabs.value.findIndex(tab => tab.path === path)
  if (tabIndex === -1) return
  
  openTabs.value.splice(tabIndex, 1)
  
  // 如果关闭的是当前标签页，切换到其他标签页
  if (path === currentPath.value && openTabs.value.length > 0) {
    const newTab = openTabs.value[Math.max(0, tabIndex - 1)]
    router.push(newTab.path)
  } else if (openTabs.value.length === 0) {
    // 如果没有打开的标签页，跳转到默认页面
    router.push('/refund')
  }
}

// 监听路由变化，自动添加标签页
watch(
  () => route.name,
  (newRouteName) => {
    if (newRouteName && pageConfigs[newRouteName]) {
      addTab(newRouteName, route.path)
    }
  },
  { immediate: true }
)

const handleLogout = async () => {
  // 关闭下拉菜单
  closeDropdown()
  
  // 显示确认对话框
  const confirmed = window.confirm('确定要退出登录吗？')
  if (!confirmed) {
    return
  }
  
  try {
    // 执行退出登录
    authStore.logout()
    
    // 清除所有打开的标签页
    openTabs.value = []
    
    // 跳转到登录页面
    await router.push('/login')
    
    // 显示退出成功提示
    showToast('已成功退出登录', 'success')
  } catch (error) {
    console.error('退出登录失败:', error)
    showToast('退出登录失败，请重试', 'error')
  }
}

const refreshPage = () => {
  // 触发当前页面刷新
  window.location.reload()
}

// 切换下拉菜单
const toggleDropdown = () => {
  dropdownOpen.value = !dropdownOpen.value
}

// 关闭下拉菜单
const closeDropdown = () => {
  dropdownOpen.value = false
}

// 点击外部关闭下拉菜单
const handleClickOutside = (event) => {
  if (userDropdown.value && !userDropdown.value.contains(event.target)) {
    closeDropdown()
  }
}

// Toast 提示函数
const showToast = (message, type = 'info') => {
  const toastContainer = document.getElementById('toastContainer')
  if (!toastContainer) return
  
  const toastId = 'toast-' + Date.now()
  const bgClass = type === 'success' ? 'bg-success' : type === 'error' ? 'bg-danger' : 'bg-info'
  
  const toastHtml = `
    <div id="${toastId}" class="toast align-items-center text-white ${bgClass} border-0" role="alert" aria-live="assertive" aria-atomic="true">
      <div class="d-flex">
        <div class="toast-body">
          ${message}
        </div>
        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
      </div>
    </div>
  `
  
  toastContainer.insertAdjacentHTML('beforeend', toastHtml)
  
  const toastElement = document.getElementById(toastId)
  const toast = new bootstrap.Toast(toastElement, {
    autohide: true,
    delay: 3000
  })
  
  toast.show()
  
  // 自动清理DOM
  toastElement.addEventListener('hidden.bs.toast', () => {
    toastElement.remove()
  })
}

// 组件挂载时初始化认证状态
onMounted(async () => {
  await authStore.initAuth()
  if (!authStore.isAuthenticated) {
    router.push('/login')
  }
  
  // 添加点击外部关闭下拉菜单的事件监听器
  document.addEventListener('click', handleClickOutside)
})

// 组件卸载时清理事件监听器
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.dashboard {
  padding-top: 76px; /* 为固定导航栏留出空间 */
}

.navbar {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 1030;
}

.navbar-brand {
  font-weight: 600;
  font-size: 1.1rem;
  text-decoration: none;
}

.main-content {
  min-height: calc(100vh - 76px);
}

/* 侧边栏样式 */
.sidebar {
  position: fixed;
  top: 76px;
  bottom: 0;
  left: 0;
  z-index: 100;
  padding: 0;
  box-shadow: inset -1px 0 0 rgba(0, 0, 0, 0.1);
  background-color: #f8f9fa !important;
  overflow-y: auto;
}

.sidebar .nav-link {
  color: #212529;
  padding: 12px 20px;
  border-radius: 0;
  transition: all 0.15s ease-in-out;
  display: flex;
  align-items: center;
  font-weight: 500;
  text-decoration: none;
}

.sidebar .nav-link i {
  margin-right: 10px;
  font-size: 1.1rem;
  width: 20px;
  text-align: center;
}

.sidebar .nav-link:hover {
  background-color: rgba(13, 110, 253, 0.1);
  color: #0d6efd;
}

.sidebar .nav-link.active {
  background-color: #0d6efd;
  color: white;
}

.sidebar .nav-link.active:hover {
  background-color: #0d6efd;
  color: white;
}

/* 主内容区域样式 */
main {
  margin-left: 0;
}

@media (min-width: 768px) {
  main {
    margin-left: 16.66667%;
  }
}

@media (min-width: 992px) {
  main {
    margin-left: 16.66667%;
  }
}

.page-content {
  animation: fadeIn 0.3s ease-in;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

/* 标签页样式 */
.tab-navigation {
  border-bottom: 1px solid #dee2e6;
}

.tab-navigation .nav-tabs {
  border-bottom: none;
  margin-bottom: 0;
}

.tab-navigation .nav-link {
  border: 1px solid transparent;
  border-radius: 0.375rem 0.375rem 0 0;
  padding: 0.5rem 1rem;
  color: #6c757d;
  background-color: #f8f9fa;
  margin-right: 2px;
  transition: all 0.15s ease-in-out;
  text-decoration: none;
  position: relative;
}

.tab-navigation .nav-link:hover {
  background-color: #e9ecef;
  color: #495057;
  border-color: #dee2e6 #dee2e6 transparent;
}

.tab-navigation .nav-link.active {
  background-color: #fff;
  color: #495057;
  border-color: #dee2e6 #dee2e6 #fff;
  border-bottom: 1px solid #fff;
  margin-bottom: -1px;
}

.tab-navigation .btn-close {
  font-size: 0.75rem;
  width: 1rem;
  height: 1rem;
  padding: 0;
  margin: 0;
  opacity: 0.6;
  transition: opacity 0.15s ease-in-out;
}

.tab-navigation .btn-close:hover {
  opacity: 1;
}

.tab-navigation .nav-link:hover .btn-close {
  opacity: 0.8;
}

/* 响应式设计 */
@media (max-width: 767.98px) {
  .sidebar {
    position: static;
    height: auto;
  }
  
  main {
    margin-left: 0;
  }
  
  .dashboard {
    padding-top: 56px;
  }
  
  .tab-navigation .nav-link {
    padding: 0.375rem 0.75rem;
    font-size: 0.875rem;
  }
  
  .tab-navigation .nav-link span {
    max-width: 100px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>